package com.sj.utils;

import cn.hutool.core.util.StrUtil;
import com.sj.common.exception.CustomException;
import com.sj.common.lang.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021-08-06
 * Time: 上午 11:18
 * Description: 自定义工具类
 *
 * @author xiaoqi
 * @since 2021-08-06
 */
@Component
public class MineUtils {

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 合并多个集合
     *
     * @param lists
     * @return
     */
    public List concatList(List... lists) {
        List<Object> list = new ArrayList<>();
        for (List<Object> tempList : lists) {
            for (Object temp : tempList) {
                list.add(temp);
            }
        }
        return list;
    }


    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".tif") ||
                FilenameExtension.equalsIgnoreCase(".tiff")) {
            return "image/tiff";
        }
        throw new CustomException("文件格式错误，请上传.jpg,.jpeg,.png,.gif,.tiff类型的图片文件");
    }


    /**
     * 校验验证码逻辑
     *
     * @param request
     */
    public void validate(HttpServletRequest request) {
        String key = request.getParameter("key");
        String code = request.getParameter("code");
        this.validate(key, code);
    }


    /**
     * 校验验证码逻辑
     *
     * @param key  验证码唯一id
     * @param code 验证码
     */
    public void validate(String key, String code) {
        // 如果key 或者 code 为空
        if (StrUtil.isBlankOrUndefined(key) || StrUtil.isBlankOrUndefined(code)) {
            throw new CustomException("验证码错误");
        }

        // 判断验证码是否相同
        if (!code.equalsIgnoreCase(String.valueOf(redisUtil.hget(Const.CAPTCHA_KEY, key)))) {
            throw new CustomException("验证码错误");
        }

        // 删除原本验证码
        redisUtil.hdel(Const.CAPTCHA_KEY, key);
    }

}